<template>
  <view class="container">
    <!-- 顶部搜索栏 -->
    <view class="header">
      <view class="user-avatar" @click="goToMine">
        <image v-if="avatarUrl" :src="avatarUrl" class="avatar-img" mode="aspectFill" @error="onImgError('avatar')"></image>
        <uni-icons v-else type="person-filled" size="24" color="#333"></uni-icons>
      </view>
      <view class="search-bar" @click="goToSearch">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <text class="search-placeholder">请输入症状/疾病</text>
      </view>
      <view class="notification">
        <uni-icons type="notification" size="24" color="#333"></uni-icons>
      </view>
    </view>
    
    <!-- Banner区域：轮播图 -->
    <view class="banner">
      <swiper class="banner-swiper" :autoplay="true" :interval="4000" :duration="500" :circular="true" :indicator-dots="true">
        <swiper-item v-for="(img, i) in bannerList" :key="i">
          <image :src="img" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
      <view class="banner-content">
        <text class="banner-title"></text>
      </view>
    </view>
    
    <!-- 知识宝典 -->
    <view class="section card">
      <view class="section-title">知识宝典</view>
      <view class="knowledge-grid">
        <view class="knowledge-item" @click="goToSymptoms">
          <view class="knowledge-image">
            <image src="/static/images/nice/new1.jpeg" mode="aspectFit"></image>
          </view>
          <text class="knowledge-title">常见病症</text>
        </view>
        <view class="knowledge-item" @click="goToDrugs">
          <view class="knowledge-image">
            <image src="/static/images/nice/new2.jpg" mode="aspectFit"></image>
          </view>
          <text class="knowledge-title">常用药品</text>
        </view>
      </view>
    </view>
    
    <!-- 问诊咨询 -->
    <view class="section card">
      <view class="section-title">问诊咨询</view>
      <view class="consultation-grid">
        <view class="consultation-item" v-for="item in consultationList" :key="item.id" @click="goToConsultation(item)">
          <view class="consultation-image">
            <image :src="item.image" mode="aspectFit"></image>
          </view>
          <text class="consultation-name">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- AI问诊与健康咨询 -->
    <view class="section card">
      <view class="section-title">AI问诊与健康咨询</view>
      <view class="ai-health-grid">
        <view class="ai-health-item" @click="goToAI">
          <view class="ai-health-image">
            <image src="/static/images/nice/new4.jpg" mode="aspectFit"></image>
          </view>
          <text class="ai-health-title">症状评估</text>
          <text class="ai-health-desc">智能自测 · 症状分析</text>
        </view>
        <view class="ai-health-item" @click="goToHealth">
          <view class="ai-health-image">
            <image src="/static/images/nice/new3.png" mode="aspectFit"></image>
          </view>
          <text class="ai-health-title">健康咨询</text>
          <text class="ai-health-desc">健康知识 · 在线咨询</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { getDepartmentList } from '@/api/department'
import config from '@/config'
import { isHttp } from '@/utils/validate'
export default {
  data() {
    return {
      consultationList: [],
      // 本地兜底资源
      avatarLocal: '',
      // 临时指向已存在的 nice 目录资源，等文件迁移至 banner 目录后再切回
      bannerLocal: '/static/images/nice/nice1.jpeg',
      bannerList: [
        '/static/images/nice/nice1.jpg?v=1',
        '/static/images/nice/nice2.jpg?v=1',
        '/static/images/nice/nice3.jpg?v=1'
      ],
      deptImgMap: {
        '内科': '/static/images/dept/internal.png',
        '眼科': '/static/images/dept/ophthalmology.png',
        '骨科': '/static/images/dept/orthopedics.png',
        '小儿科': '/static/images/dept/pediatric.png',
        '传染病科': '/static/images/dept/infectious.png',
        '皮肤性病': '/static/images/dept/dermatology.png',
        '耳鼻喉科': '/static/images/dept/ent.png',
        '精神病科': '/static/images/dept/psychiatry.png'
      },
      deptDefaultImg: '/static/images/profile.jpg'
    }
  },
  computed: {
    ...mapState({
      avatar: state => state.user && state.user.avatar
    })
    ,
    avatarUrl() {
      return this.avatarLocal || this.avatar
    }
  },
  onShow() {
    // 确保进入首页时获取并刷新用户信息（头像等）
    if (this.$store && this.$store.dispatch) {
      this.$store.dispatch('GetInfo').catch(() => {})
    }
    // 拉取后端科室列表
    this.loadDepartments()
  },
  methods: {
    goToSearch() {
      // 跳转到搜索页面
      uni.navigateTo({
        url: '/pages/search/index'
      })
    },
    goToSymptoms() {
      // 跳转到常见病症页面
      uni.navigateTo({
        url: '/pages/symptoms/index'
      })
    },
    goToDrugs() {
      // 跳转到症状页面的药品标签
      uni.navigateTo({
        url: '/pages/symptoms/index?tab=drugs'
      })
    },
    goToConsultation(item) {
      const departmentMap = {
        '内科': 'internal',
        '眼科': 'ophthalmology', 
        '骨科': 'orthopedics',
        '小儿科': 'pediatric',
        '传染病科': 'infectious',
        '皮肤性病': 'dermatology',
        '耳鼻喉科': 'ent',
        '精神病科': 'psychiatry'
      }
      const department = departmentMap[item.name] || 'internal'
      const deptId = item.id
      const deptName = encodeURIComponent(item.name || '')
      uni.navigateTo({
        url: `/pages/doctors/index?deptId=${deptId}&deptName=${deptName}&department=${department}`
      })
    },
    goToMine() {
      // 跳转到“我的”页
      uni.switchTab({ url: '/pages/mine/index' })
    },
    async loadDepartments() {
      try {
        const res = await getDepartmentList()
        const list = Array.isArray(res) ? res : (res.data || [])
        // 映射并排序：{id, name, image, order}
        const mapped = list.map((d, idx) => {
          const name = d.name || d.deptName || d.departmentName || ''
          const id = d.id || d.deptId || idx
          let img = d.deptIcon || d.imageUrl || d.image || d.iconUrl || d.icon || d.logo || d.pic || d.picture || ''
          if (img) {
            if (!isHttp(img) && img.indexOf('/') !== 0) {
              img = `${config.baseUrl}${img}`
            }
          } else {
            // 未提供后端图片则按名称映射到本地
            img = this.deptImgMap[name] || this.deptDefaultImg
          }
          const order = d.sort || d.orderNum || d.order || d.seq || d.sequence || id || idx
          return { id, name, image: img, order }
        }).sort((a, b) => {
          if (a.order === b.order) return (a.name || '').localeCompare(b.name || '')
          return (a.order || 0) - (b.order || 0)
        })
        this.consultationList = mapped
      } catch (e) {
        console.error('加载科室列表失败', e)
        this.$modal && this.$modal.msg('获取科室列表失败')
      }
    },
    onDeptImgError(index) {
      if (this.consultationList && this.consultationList[index]) {
        this.$set ? this.$set(this.consultationList[index], 'image', this.deptDefaultImg)
                  : (this.consultationList[index].image = this.deptDefaultImg)
      }
    },
    onImgError(type) {
      if (type === 'avatar') {
        this.avatarLocal = '/static/images/profile.jpg'
      } else if (type === 'banner') {
        this.bannerLocal = '/static/images/banner/banner1.png'
      }
    },
    goToAI() {
      // 跳转到新的AI症状检查页
      uni.showToast({ title: '打开症状评估...', icon: 'none', duration: 700 })
      uni.navigateTo({ url: '/pages/ai/symptom/index' })
    },
    goToHealth() {
      uni.navigateTo({ url: '/pages/consult/health' })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  
  .user-avatar {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    .avatar-img { width: 100%; height: 100%; }
  }
  
  .search-bar {
    flex: 1;
    margin: 0 20rpx;
    height: 60rpx;
    background-color: #f8f8f8;
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    
    .search-placeholder {
      margin-left: 10rpx;
      color: #999;
      font-size: 28rpx;
    }
  }
  
  .notification {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.banner {
  margin: 20rpx 30rpx;
  height: 300rpx;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  
  .banner-swiper { width: 100%; height: 100%; }
  image { width: 100%; height: 100%; }
  
  .banner-content {
    position: absolute;
    left: 40rpx;
    top: 50%;
    transform: translateY(-50%);
    
    .banner-title {
      color: #fff;
      font-size: 36rpx;
      font-weight: bold;
      line-height: 1.4;
    }
  }
}

.section { margin: 30rpx 30rpx 0; }
.card {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(0,0,0,0.04);
}
.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.knowledge-grid {
  display: flex;
  gap: 24rpx;
  
  .knowledge-item {
    flex: 1;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 36rpx 24rpx;
    text-align: center;
    box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.04);
    
    .knowledge-image {
      width: 140rpx;
      height: 140rpx;
      margin: 0 auto 20rpx;
      
      image {
        width: 100%;
        height: 100%;
      }
    }
    
    .knowledge-title {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.consultation-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx 20rpx;
  
  .consultation-item {
    width: calc(50% - 10rpx);
    text-align: center;
    background: #fff;
    border-radius: 16rpx;
    padding: 28rpx 10rpx;
    box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.04);
    
    .consultation-image {
      width: 120rpx;
      height: 120rpx;
      margin: 0 auto 10rpx;
      
      image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
    
    .consultation-name {
      font-size: 26rpx;
      color: #555;
    }
  }
}

/* AI问诊与健康咨询 */
.ai-health-grid {
  display: flex;
  gap: 24rpx;
  
  .ai-health-item {
    flex: 1;
    background: #fff;
    border-radius: 16rpx;
    padding: 28rpx 24rpx;
    text-align: center;
    box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.04);
  }
  .ai-health-image {
    width: 140rpx;
    height: 140rpx;
    margin: 0 auto 12rpx;
    image { width: 100%; height: 100%; }
  }
  .ai-health-title { font-size: 28rpx; color: #333; font-weight: 600; }
  .ai-health-desc { display:block; margin-top: 8rpx; font-size: 24rpx; color: #777; }
}
</style>
